package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * redis优化查询所有店铺类型集合
     *
     */
    @Override
    public Result queryTypeList() {
        // 先看看 redis 缓存里面有没有存入店铺类型集合
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_KEY, 0, 1);
        if (CollectionUtil.isNotEmpty(shopTypeList)) {
            // 缓存里有直接返回
            return Result.ok(shopTypeList);
        }
        // 没有缓存,从数据库查询
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        // 如果数据库没有则返回异常
        if (shopTypes.isEmpty()) {
            return Result.fail("查询店铺类型异常");
        }
        // 设置到缓存里面
        shopTypes.stream().
                forEach(shopType -> {
                    stringRedisTemplate.opsForList().leftPushAll(RedisConstants.CACHE_SHOP_KEY,JSONUtil.toJsonStr(shopTypes));
                });
        return Result.ok(shopTypes);
    }

}
